import { getorganizationList } from '@/api/account';

let leveltion = {
	organization:[],
}

let echoarr = []

// 获取架构信息
export async function getation(){
	return new Promise((resolve)=>{
		getorganizationList({}).then(res=>{
			if(res.state == 200){
				leveltion.organization = []
				for(let item of res.data){
					item.value = item.ao_id
					item.label = item.organization_name
					item.leaf = true
					item.children = []
					leveltion.organization.push(item)
				}
				resolve(leveltion.organization)
			}
		})
	})
}

// 整理架构信息
// 注：1返回数组，2返回层级信息
let arrange = async (e,k) =>{
	let arr = []
	let value = k || 0
	// if(leveltion.organization.length == 0){
		await getation()
	// }

	if(e == 1){
		arr = leveltion.organization
	}
	if(e == 2){
		let list = []
		for(let item of leveltion.organization){
			if(item.pid == value){
				list.push(item)
			}
			if(leveltion.organization.length == 1 && value == 0){
				list.push(item)
			}
		}
		arr = final(list)
	}
	return arr 
}

// 检测是否为最后一个
let final = (e) =>{
	for(let item of e){
		for(let ime of leveltion.organization){
			if(item.ao_id == ime.pid){
				item.leaf = false
			}
		}
	}
	return e
}

// 层级回显
// e 被选中的ID
let echo = async (e) =>{
	echoarr = []
	await getation()
	getecho(e)
	return echoarr
}

// 回显筛选
let getecho = (e) =>{
	for(let item of leveltion.organization){
		if(item.ao_id == e){
			echoarr.unshift(item.ao_id)
			getecho(item.pid)
		}
	}
}

export default {
	arrange,
	echo
}